package com.erps.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.erps.CommonUtils.AppConfig;
import com.erps.CommonUtils.StringEx;
import com.erps.dao.ErspSysLogDao;
import com.hmkj.entity.ErspSysLog;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

public class CheckLoginInterceptor implements Interceptor {
	private static ErspSysLogDao LogDao = null;

	public void intercept(Invocation ai) {
		if (LogDao == null)
			LogDao = new ErspSysLogDao();
		ErspSysLog vo = new ErspSysLog();
		vo.setMethod_argv(ai.getArgs().toString());
		vo.setService_name(ai.getControllerKey());
		vo.setMethod_name(ai.getMethodName());
		vo.setIpaddr(ai.getController().getRequest().getRemoteAddr());
		new ErspSysLogDao().add(vo);
		String cKey = ai.getActionKey();
		//
		if ((cKey.lastIndexOf("/services") > -1) || (cKey.lastIndexOf("/add") > -1) || (cKey.lastIndexOf("save") > -1)) {
			Controller controller = ai.getController();
			HttpServletRequest request = controller.getRequest();
			HttpServletResponse response = controller.getResponse();
			HttpSession session = request.getSession();
			if ((session == null) || StringEx.isEmpty(session.getAttribute(AppConfig.SESSION_USERID))) {
				// 用户登录验证失败，跳转到登录页面
				try {
					String cUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/ersp_sys/login";
					response.sendRedirect(cUrl);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		try {
			ai.invoke();
		} catch (Exception e) {

		}
	}
}